﻿/******************************************************************
*
* ItemQuery
* Just work for Cn.Cellula Business Framework
* Autor:  AnyRock@mending.cn
* Create: 2011-5-4
* Last:   2011-5-4
*
******************************************************************/
var ItemQuery = function (rHd) {
    var __hd = (typeof (rHd) == "string") ? rHd : "itemQuery";
    var __ajax = null;
    var __data = null;
    var __listBox = null;
    var __listBoxId = null;
    var __requestUrl = null;
    var __getQueryKey = function () {
        return $("#" + fixId("txt_QueryKey")).value;
    };
    var __getCategoryKey = function () {
        return $("#" + fixId("ddl_Category")).value; ;
    };
    var __buildParms = function () {
        var parm = "";
        try {
            var p_ck = __getCategoryKey();
            parm += "&ck=" + p_ck;
            var p_qk = __getQueryKey();
            if (typeof (p_qk) == "string" && p_qk.length > 0) {
                parm += "&iqk=" + encodeURI(p_qk);
            }

            var atls = $("#" + fixId("hid_AtlKeys")).value.split(',');
            if (atls != null && atls.length > 0) {
                var _val = null;
                var _obj = null;
                var _ref = null;
                var _refKey = null;
                var _type = null;
                for (var i = 0; i < atls.length; i++) {
                    _obj = $("#" + atls[i]);
                    if (_obj == null) continue;
                    _type = _obj.getAttribute("atl_type");
                    _val = encodeURI(_obj.value);
                    if (_val != null && _val != "") {
                        if (_type == "item") {
                            _ref = $("#" + atls[i] + "_ref");
                            _refKey = encodeURI(_ref.value);
                            parm += "&a" + i + "=" + _refKey;
                        } else {
                            parm += "&a" + i + "=" + _val;
                        }
                        if ((_type === "dt"
                            || _type === "dm"
                            || _type === "dy"
                            || _type === "year"
                            || _type === "month"
                            ) && $("#" + atls[i] + "2") != null) {
                            parm += "&a" + i + "_2=" + encodeURI($("#" + atls[i] + "2").value);
                        }
                    }
                }
            }
        } catch (e) {
            alert(e.Message);
            return null;
        }
        return parm;
    };
    var __markQueryKey = function (rContent, rQueryKey) {
        var _qk = (rQueryKey == null) ? __getQueryKey() : rQueryKey;
        if (typeof (rContent) == "string" && typeof (_qk) == "string" && _qk.length > 0 && rContent.indexOf(_qk) != -1) {
            rContent = rContent.replaceAll(_qk, '<font class="item_SubGridViewQK">' + _qk + '</font>', "gi");
            _qk = null;
        }
        return rContent;
    };
    var __loadData = function (rAction) {
        var parm = __buildParms();
        if (parm != null) {
            __requestUrl = "Ws/_Item.aspx?act=" + rAction + parm + "&rm=" + jskitUtil.guid();
            __showLoading();
            __ajax = new JskitXmlHttpAction(__requestUrl, __hd + ".__loadDataCallback", "text");
        }
    };
    this.__loadDataCallback = function (rData) {
        __ajax = null;
        __listBox.innerHTML = "";
        try {
            eval("__data = " + rData + ";");
        } catch (e) {
            __response("[Load data error:]<a href='" + __requestUrl + "' target='_blank'>" + e.message + "</a>");
            return;
        }
        if (__data == null) {
            __response("[Load data error:]<a href='" + __requestUrl + "' target='_blank'>Invalid Data Format</a>");
            return;
        }
        __buildContent();
    };
    var __loadReport = function (rAction) {
        var parm = __buildParms();
        if (parm != null) {
            __requestUrl = "Ws/_Item.aspx?act=" + rAction + parm + "&rm=" + jskitUtil.guid();
            __showLoading();
            __ajax = new JskitXmlHttpAction(__requestUrl, __hd + ".__loadReportCallback", "text");
        }
    };
    var __countColumn = function (rData, rRule, rVal) {
        if (rRule == "countrule_sum" || rRule == "countrule_avg") {
            if (isNaN(parseFloat(rVal))) {
                rVal = 0;

            }
            if (!isNaN(parseFloat(rData))) {
                rVal = parseFloat(rVal) + parseFloat(rData);
            } else if (!isNaN(parseInt(rData))) {
                rVal = parseInt(rVal) + parseInt(rData);
            }
        } else if (rRule == "countrule_count") {
            if (isNaN(parseFloat(rVal))) { rVal = 0; }
            rVal++;
        }
        return rVal;
    };
    this.__loadReportCallback = function (rData) {
        __ajax = null;
        __listBox.innerHTML = "";
        try {
            eval("__data = " + rData + ";");
        } catch (e) {
            __response("[Load data error:]<a href='" + __requestUrl + "' target='_blank'>" + e.message + "</a>");
            return;
        }
        var _str = new Array();
        _str.push('<div class="item_GridView_Title">');
        if (__data != null && __data.length == 2 && __data[1].length > 0) {
            _str.push('共找到<span>' + (__data[1].length) + '</span>条符合条件的记录');
            _str.push(' [<a href="javascript:' + __hd + '.export2Csv()" >导出到CSV文件</a>]');
            _str.push('<iframe src="" id="ifm_' + __hd + '" style="display:none"></iframe>');
        } else {
            _str.push('没有找到符合条件的记录');
        }
        var _header = __data[0];
        var _rows = __data[1];
        var _sum = new Array(_header.length);
        _str.push('</div>');
        _str.push('<table class="item_GridView" cellspacing="0" cellpadding="0">');
        _str.push('<thead><tr class="item_GridViewHeader">');
        _str.push('<th>&nbsp;</th>');
        for (var j = 0; j < _header.length; j++) {
            _str.push('<th>');
            _str.push(_header[j][0]);
            _str.push('</th>');
        }
        _str.push('</tr></thead>');
        if (_rows.length > 0) {
            var _cells = null;
            _str.push('<tbody>');
            for (var i = 0; i < _rows.length; i++) {
                _cells = _rows[i];
                if (i % 2 == 0) {
                    _str.push('<tr class="item_GridViewRow">');
                } else {
                    _str.push('<tr class="item_GridViewRow2">');
                }
                _str.push('<td>' + (i + 1) + '</td>');
                for (var j = 1; j < _cells.length; j++) {
                    _str.push('<td>');
                    if (j == 1) {
                        _str.push('<a href="Admin/Item/ItemView.aspx?id='+_cells[0]+'">'+_cells[j]+'</a>');
                    } else {
                        _str.push(_cells[j]);
                    }
                    _str.push('</td>');
                    _sum[j-1] = __countColumn(_cells[j], _header[j - 1][1], _sum[j-1]);
                }
                _str.push('</tr>');
            }
            _cells = null;
            _str.push('</tbody>');
        }
        _str.push('<tfoot class="item_GridViewFooter">');
        _str.push('<tr>');
        _str.push('<td>&nbsp;</td>');
        for (var j = 0; j < _header.length; j++) {
            _str.push('<td>');
            if (_header[j][1] == "countrule_avg") {
                _str.push((_sum[j] / _rows.length));
            } else {
                _str.push(_sum[j]);
            }
            _str.push('</td>');
        }
        _str.push('</tr>');
        _str.push('</tfoot>');
        _str.push('</table>');
        _header = _rows = _sum = null;
        __response(_str.join(''));
    };
    var __export = function (rAction) {
        var parm = __buildParms();
        if (parm != null) {
            __requestUrl = "Ws/_Item.aspx?act=" + rAction + parm + "&rm=" + jskitUtil.guid();
            //__ajax = new JskitXmlHttpAction(__requestUrl, __hd + ".__exportCallback", "text");
            var ifm = $("#ifm_" + __hd);
            if (ifm != null) {
                ifm.src = __requestUrl;
            } else {
                alert("Export displyer not found!");
                return;
            }
        }
    };
    var __showLoading = function () {
        __response('<div style="background-image:url(/cellula_client/Controls/images/loading.gif);background-position:center center;background-repeat:no-repeat;width:40px;height:40px;overflow:hidden;">&nbsp;</div>');
    };

    var __buildContent = function () {
        var _extColumns = 3;
        var _expand = true;
        var _str = new Array();
        var _column = __data[0];
        var _list = __data[1];
        //_str.push("<a href='" + __requestUrl + "' target='_blank'>check</a>");
        _str.push('<div class="item_GridView_Title">');
        if (_list.length > 0) {
            _str.push('共找到<span>' + _list.length + '</span>条符合条件的记录');
            _str.push(' ，点击横栏展开详细信息');
            _str.push(' [<a href="javascript:' + __hd + '.export2Csv()" >导出到CSV文件</a>]');
            _str.push('<iframe src="" id="ifm_' + __hd + '" style="display:none"></iframe>');
        } else {
            _str.push('没有找到符合条件的记录');
        }
        _str.push('</div>');
        _str.push('<table class="item_GridView" cellspacing="0" cellpadding="0">');
        //build column
        _str.push('<thead><tr class="item_GridViewHeader"><th style="width:20px"></th>');
        _str.push('<th>名称</th>');
        _str.push('<th>编号</th>');
        _str.push('<th>分类</th>');
        _str.push('<th>标签</th>');
        _str.push('<th>文件</th>');
        _str.push('</tr></thead>');
        var _eo = null;
        var _val = null;
        _str.push('<tbody>');
        for (var j = 0; j < _list.length; j++) {
            _eo = _list[j];
            if (j % 2 == 0) {
                _str.push('<tr class="item_GridViewRow" ');
            } else {
                _str.push('<tr class="item_GridViewRow2" ');
            }
            _str.push(' onclick="' + __hd + '.expand(' + j + ')" >');
            _str.push('<td style="width:20px">' + (j + 1) + '</td>');
            _str.push('<td><a href="Admin/Item/ItemView.aspx?id=' + _eo[0] + '">' + __markQueryKey(_eo[1], null) + '</a></td>');
            _str.push('<td>' + _eo[2] + '</td>');
            _str.push('<td><a href="Admin/Item/List.aspx?cid=' + _eo[3] + '">' + _eo[4] + '<a></td>');
            _str.push('<td>' + __markQueryKey(_eo[5], null) + '</td>');
            _str.push('<td>' + _eo[6] + '</td>');
            _str.push('</tr>');
            _str.push('<tr><td colspan="6" class="item_SubGridView_box" ik="' + _eo[0] + '" id="' + __hd + '_idx_' + j + '" style="display:none">');
            _str.push('</td></tr>');
        }
        _str.push('</tbody>');
        _str.push('</table>');
        __response(_str.join(''));
    };
    var __response = function (rStr) {
        if (__listBox == null) {
            __listBox = $("#" + __listBoxId);
        }
        if (__listBox == null) {
            alert("list box not found");
        } else {
            __listBox.innerHTML = rStr;
        }
    };
    ////////////////////////////////////////////////////////////////////////////////////
    var __showSubLoading = function () {
        __activeSubBox.innerHTML = '<div style="background-image:url(/cellula_client/Controls/images/loading.gif);background-position:center center;background-repeat:no-repeat;width:40px;height:40px;overflow:hidden;">&nbsp;</div>';
    };
    var __responseSub = function (rStr) {
        if (__activeSubBox == null) {
            alert("list box not found");
        } else {
            __activeSubBox.innerHTML = rStr;
        }
    };
    var __subData = null;
    var __activeSubBox = null;
    var __requestSubUrl = null;
    this.expand = function (rIdx) {
        __activeSubBox = $("#" + __hd + "_idx_" + rIdx);
        if (__activeSubBox != null) {
            if (__activeSubBox.style.display == "none") {//load atl data
                __activeSubBox.style.display = "block";
                if (__activeSubBox.getAttribute("isloaded") !== "1") {//not load yeat
                    __requestSubUrl = "Ws/_Item.aspx?act=qad&id=" + __activeSubBox.getAttribute("ik") + "&rm=" + jskitUtil.guid();
                    __showSubLoading();
                    __ajax = new JskitXmlHttpAction(__requestSubUrl, __hd + ".__loadAtlDataCallback", "text");
                    __activeSubBox.setAttribute("isloaded", "1");
                }
            } else {
                __activeSubBox.style.display = "none";
                __ajax = null;
            }
        } else {
            alert("box not found!");
        }
    };
    this.__loadAtlDataCallback = function (rData) {
        __ajax = null;
        try {
            eval("__subData = " + rData + ";");
        } catch (e) {
            __responseSub("[Load data error:]<a href='" + __requestSubUrl + "' target='_blank'>" + e.message + "</a>");
            return;
        }
        if (__subData == null) {
            __responseSub("[Load data error:]<a href='" + __requestSubUrl + "' target='_blank'>Invalid Data Format</a>");
            return;
        }
        __buildSubContent();
    };

    var __buildSubContent = function () {
        var _str = new Array();
        var _obj = null;
        _str.push('<table cellspacing="0" cellpadding="0" border="0" class="item_SubGridView">');
        var _content = null;
        var _qk = __getQueryKey();
        for (var i = 0; i < __subData.length; i++) {
            _obj = __subData[i];
            _str.push('<tr class="item_SubGridViewRow">');
            _str.push('<td class="item_SubGridViewTitle">' + _obj[1] + '：</td>');
            _content = __markQueryKey(_obj[2]);
            if (_obj[3] != "") {
                _str.push('<td class="item_SubGridViewData"><a href="Admin/Item/ItemView.aspx?id=' + _obj[3] + '">' + _content + '</a></td>');
            } else {
                _str.push('<td class="item_SubGridViewData">' + _content + '</td>');
            }
            _str.push('</tr>');
        }
        _str.push('</table>');
        __activeSubBox.innerHTML = _str.join('');
        __activeSubBox = null;
    };
    this.setListBoxId = function (rId) {
        __listBoxId = rId;
    };
    this.export2Csv = function () {
        __export("exp");
    };
    this.load = function () {
        if ($("#rad_list").checked) {
            __loadData("q");
        } else {
            __loadReport("qr");
        }
    };
};